<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\user\controller;

use api\common\controller\ApiBaseController;
use api\portal\model\MerchModel;
use cmf\model\UserModel;
use think\facade\Db;
use wxapp\aes\WXBizDataCrypt;

/**
 * Class LoginController
 * @package api\user\controller
 */
class LoginController extends ApiBaseController
{


    /**
     *  微信登录code
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCode()
    {

        $appid = ENV('APPID');
        $secret = ENV('SECRET');
        $code = $this->request->post('code');
        $data = $this->request->post();
        $accessToken = $this->getAccessToken();
        $LoginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";

        if ($this->is_error($accessToken)) {
            return $this->error($accessToken);
        }
        $res = cmf_curl_get($LoginUrl);
        $res = json_decode($res, true);

        if (isset($res['errcode'])) {
            return $this->error($res['errmsg']);
        }

        $data['openid'] = $res['openid'];
        cache('session_key', $res['session_key'], 7200);
        return $this->doLogin($data);
    }

    /**
     * 注册
     */
    public function register($data)
    {
        $insertData = [
            'user_type' => 2,
            'sex' => $data['userInfo']['gender'],
            'create_time' => time(),
            'user_nickname' => $data['userInfo']['nickName'],
            'avatar' => $data['userInfo']['avatarUrl'],
            'last_login_ip' => $this->get_client_ip(),
            'openid' => $data['openid'],
            // 'unionid' => $data['userInfo']['unionid'],
        ];
        $userModel = new UserModel();
        $usreId = $userModel->insertGetId($insertData);
        $currentTime = time();
        $expireTime = $currentTime + 24 * 3600 * 180;
        $token = md5(uniqid()) . md5(uniqid());
        Db::name("user_token")->insert([
            'token' => $token,
            'user_id' => $usreId,
            'expire_time' => $expireTime,
            'create_time' => $currentTime,
            'device_type' => $this->deviceType
        ]);
        $this->user = $userModel->where('id', $usreId)->find();
        $this->userId = $usreId;
        $this->userType = $this->user['user_type'];
        return $this->success('登录成功', ['token' => $token]);
    }


    /**
     * 执行登录操作
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function doLogin($data)
    {
        $openid = $data['openid'];
        $userModel = new UserModel();
        $user = $userModel->where(['openid' => $openid, 'user_status' => 1])->find();
        if (empty($user)) {
            return $this->register($data);
        }
        $currentTime = time();
        $expireTime = $currentTime + 24 * 3600 * 180;
        $token = md5(uniqid()) . md5(uniqid());
        Db::name("user_token")
            ->where('user_id', $user['id'])
            ->update([
                'token' => $token,
                'expire_time' => $expireTime,
                'create_time' => $currentTime
            ]);
        $this->user = $user;
        $this->userId = $user['id'];
        $this->userType = $user['user_type'];

        $merch = MerchModel::where(['user_id' => $user['id'],'status'=>1])->find();
        if (!empty($merch)) {
            $this->merchId = $merch['id'];
        }

        unset($user['last_login_ip']);
        unset($user['user_pass']);
        return $this->success('登录成功', ['token' => $token, 'userinfo' => $user]);
    }

    /**
     * 登录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login()
    {
        $data = $this->request->post();
        $openid = $data['openid'];
        if (empty($openid)) {
            return $this->error('数据错误');
        }
        return $this->doLogin($data);

    }

    /**
     * 退出
     * @throws \think\db\exception\DbException
     */
    public function loginOut()
    {
        $userId = $this->getUserId();
        Db::name('user_token')->where([
            'token' => $this->token,
            'user_id' => $userId,
        ])->update(['token' => '']);

        $this->success("退出成功!");
    }

    /**
     * 绑定手机号
     */
    public function bindMobile()
    {
        $data = $this->request->post();
        if (empty($data)) {
            return $this->error('手机号不能为空!');
        }

        if (empty($this->userId)) {
            return $this->error('token已过期!');
        }

        $mobile = $this->decrypt($data);
        if ($mobile != false) {
            $count = Db::name("user")
                ->where('mobile', $mobile)
                ->find();
            if ($count) {
                return $this->error('手机号已存在');
            }
            Db::name("user")
                ->where('id', $this->userId)
                ->update([
                    'mobile' => $mobile,
                ]);

            $user = Db::name("user")->where(['id' => $this->userId, 'user_status' => 1])->find();
            $this->user = $user;

            $this->success("绑定成功!", ['userinfo' => $user]);
        }
        return $this->error('绑定失败');
    }


    /**
     * 对密文进行解密
     * @param string $aesCipher 需要解密的密文
     * @param string $aesIV 解密的初始向量
     * @return string 解密得到的明文
     */
    public function decrypt($data)
    {
        $appid = ENV('APPID');
        $encryptedData = $data['encryptedData'];
        $iv = $data['iv'];

        $sessionKey = cache('session_key');
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        if ($errCode == 0) {
            return $data['phoneNumber'];
        } else {
            return false;
        }
    }

}
